from fastapi import Depends, APIRouter
from fastapi.security import OAuth2PasswordRequestForm

from authentication.jwt import login_authentication, create_access_token
from domain.authentication import Token, TokenData, User
from authentication.utils import get_custom_oauth_form

auth_router = APIRouter(
    prefix="/api/auth",
    tags=['authentication']
)


@auth_router.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    # form data preprocessing
    ret_oauth_form = get_custom_oauth_form(form_data)
    # authenticate user with its uuid
    login_token_data = TokenData(
        uuid=ret_oauth_form.uuid,
        username=ret_oauth_form.name,
        email=ret_oauth_form.email,
        password=ret_oauth_form.password
    )
    user: User = await login_authentication(login_token=login_token_data)
    access_token = create_access_token(
        data={
            "sub": user.uuid.hex,
            "name": user.username,
            "email": user.email,
            "password": user.password
        },  # sub should be a unique identifier across the entire application, and it should be a string
    )
    return {"access_token": access_token, "token_type": "bearer"}


